from django.shortcuts import get_object_or_404
from django.contrib.auth.decorators import user_passes_test

from django.http import HttpResponse, HttpResponseRedirect

from assets.models import Format

from transcodercaches.models import PreCacheRule, PreCacheRule_Argument
  
from assets.util import HttpResponseSerialized, Fields

def SerializeRule(rule):
  d = Fields(rule, 'id', 'name')
  d['dstFormat'] = rule.dstFormat.name if rule.dstFormat else 'None'
  d['srcFormats'] = list(rule.srcFormats.all().values_list('name', flat=True))
  d['arguments'] = list(rule.arguments.all().values_list('name', 'value'))
  return d


@user_passes_test(lambda u: u.is_superuser)  
def precacherule_formats(request, name):
  """
  Return a list of supported source formats for the destination format that is set.
  """
  rule = get_object_or_404(PreCacheRule, name=name)
  from damn import TranscoderInstance
  trans = TranscoderInstance()
  formats = []
  for srcFormat, transcoders in trans.transcoders.items():
    for transcoder in transcoders:
      dsts = transcoder.convert_map[srcFormat]
      dsts = dsts if type(dsts) == type([]) else [dsts]
      if rule.dstFormat and rule.dstFormat.name in dsts:
        formats.append(srcFormat)
           
  return HttpResponseSerialized(request, formats) 


@user_passes_test(lambda u: u.is_superuser)  
def precacherule_arguments(request, name):
  """
  Return a list of supported arguments for the set destination and source formats.
  """
  rule = get_object_or_404(PreCacheRule, name=name)
  from damn import TranscoderInstance
  trans = TranscoderInstance()
  
  arguments = {}
  for srcFormat, transcoders in trans.transcoders.items():
    if srcFormat in rule.srcFormats.all().values_list('name', flat=True):
      for transcoder in transcoders:
        dsts = transcoder.convert_map[srcFormat]
        dsts = dsts if type(dsts) == type([]) else [dsts]
        if rule.dstFormat and rule.dstFormat.name in dsts:
          if hasattr(transcoder, 'options_map') and srcFormat in transcoder.options_map:
            for o in transcoder.options_map[srcFormat]:
              name = str(o[0])
              typeName = str(getattr(o[1], '__name__', 'unknown type'))
              if not name in arguments: 
                arguments[name] = {'type': typeName, 'default': str(o[2]), 'formats': [srcFormat], 'conflicts': []}
              else:
                if arguments[name]['type'] != typeName:
                  arguments[name]['conflicts'].append[[ arguments[name][-1] , srcFormat]] # last, new
                arguments[name]['formats'].append(srcFormat)
           
  return HttpResponseSerialized(request, arguments)


